package cn.zhfeat.hatch.web.controller.system;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zhfeat.utils.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @explain
 * @author ZhangHao
 * @data 2017年7月1日
 */
@Controller
@RequestMapping("/api/uploadfile")
public class PublicUploadFileController {

	@Value("#{configProperties['UplaodBaseUrl']}")
	private String UPLOAD_BASE_URL;
	private static String basePath;
	private static String fileVisitBasePath;
	private Logger log = Logger.getLogger(PublicUploadFileController.class);

	public PublicUploadFileController() {
//		String temp_basePath = PropertyUtil.getValueByKey("conf/file-site.properties", "fileUploadBasePath");
//		System.out.println("==小文件上传开启成功==");
//		if (temp_basePath == null || temp_basePath.isEmpty()) {
//			basePath = null;
//			fileVisitBasePath = null;
//			System.out.println("上传路径为：本地模式");
//		} else {
//			basePath = temp_basePath;
//			fileVisitBasePath = PropertyUtil.getValueByKey("conf/file-site.properties", "fileVisitBasePath");
//			System.out.println("上传路径为：" + basePath);
//		}
	}

	/**
	 * 
	 * @explain 上传文件接口
	 * @author ZhangHao
	 * @data 2017年6月17日
	 */
	/*
	 * @RequestMapping(value="/file" ,method = RequestMethod.POST,produces =
	 * "application/json;charset=UTF-8") public @ResponseBody Object
	 * file(HttpServletRequest request,HttpServletResponse response
	 * ,@RequestParam(value = "typename",required = false)String typename
	 * ,@RequestParam(value = "isFile",required = false)Boolean isFile ){
	 * System.out.println("111111111111111");
	 * 
	 * response.setHeader("Access-Control-Allow-Origin","*");
	 * response.setHeader("Access-Control-Allow-Methods","GET,POST"); if
	 * (isFile!=null&&isFile==true) { typename+="_FILE";//加入文件类型标记 }
	 * 
	 * JSONObject jsonObject=
	 * FileUploadUtils.getinstance().UploadFile(request,typename);
	 * System.out.println(jsonObject); return (jsonObject); }
	 */

	@RequestMapping(value = "/file", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Object file(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "typename", required = false) String typename,
			@RequestParam(value = "isFile", required = false) Boolean isFile,
			@RequestParam(value = "fileType", required = false) String fileType,
			@RequestParam(value = "filePath", required = false) String filePath,
			@RequestParam(value = "maxSize", required = false) Long maxSize) {
		String projectUrl = "";
		String result = "";
		JSONObject jsonObject = new JSONObject();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(typename);// 获取表单
			if(multipartFile == null) {
				Map<String, MultipartFile> map = multipartRequest.getFileMap();
				for (String fname : map.keySet()) {
		            // 获得文件：
		            multipartFile = multipartRequest.getFile(fname);
				}
			}
			// 获取上传文件限制大小
			String filename = multipartFile.getOriginalFilename();// 获取文件名
            // 获取文件的大小
			long fileSize = multipartFile.getSize();
			//判断文件大小是否超过最大限制
			if(maxSize != null) {
				if(maxSize < fileSize) {
					jsonObject.put("status", "201");
					jsonObject.put("message", "文件大小超过限制，上传失败");
					return jsonObject;
				}
			}
			
			
			
//			System.out.println("fileSize------->"+fileSize);
//			System.out.println("maxSize------->"+maxSize);
			if (StringUtils.isEmpty(filePath)) {
				filePath = "";
			}
			String FPATH = this.getClass().getClassLoader().getResource("/").getPath().split("/WEB-INF/")[0]
					+ "/upload/";
			if (basePath != null) {
				FPATH = basePath + "/";
			} else {
				projectUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
						+ request.getContextPath() + "/";
			}
			String originalFilename = multipartFile.getOriginalFilename();
			String extName = "";
			int lastIndexOf = originalFilename.lastIndexOf(".");
			if (lastIndexOf >= 0) {
				extName = originalFilename.substring(lastIndexOf);
			}
			String fileAllPath = "";
			if (StringUtils.isEmpty(filePath)) {
				fileAllPath = UUID.randomUUID() + extName;
			} else {
				fileAllPath = filePath + "/" + UUID.randomUUID() + extName;
			}

			if (!new File(FPATH + fileAllPath).getParentFile().exists()) {
				new File(FPATH + fileAllPath).mkdirs();
			}

			multipartFile.transferTo(new File(FPATH + fileAllPath));
			if (fileVisitBasePath != null) {
				result = fileVisitBasePath + "/" + fileAllPath;
			} else {
				result = "upload/" + fileAllPath;
			}
			if (result != "" && result != null && result.length() > 0) {
				jsonObject.put("status", "200");
				jsonObject.put("message", "文件上传成功");
				jsonObject.put("saveFilename", filename);
				// jsonObject.put("realSavePath", realSavePath);
				jsonObject.put("realSavePath", projectUrl + result);

			} else {
				jsonObject.put("message", "文件上传失败");
			}
		} catch (Exception e) {
			jsonObject.put("status", "202");
			jsonObject.put("message", "文件上传失败");
			e.printStackTrace();
		}
		return jsonObject;
	}

	@RequestMapping(value = "/uploadCKImg")
	public void uplodaImg(@RequestParam("upload") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String projectUrl = "";
			String result = "";
			String FPATH = this.getClass().getClassLoader().getResource("/").getPath().split("/WEB-INF/")[0]
					+ "/upload/";
			if (basePath != null) {
				FPATH = basePath + "/";
			} else {
				projectUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
						+ request.getContextPath() + "/";
			}
			String originalFilename = file.getOriginalFilename();
			String extName = "";
			int lastIndexOf = originalFilename.lastIndexOf(".");
			if (lastIndexOf >= 0) {
				extName = originalFilename.substring(lastIndexOf);
			}
			String fileAllPath = "";
			fileAllPath = UUID.randomUUID() + extName;
			if (!new File(FPATH + fileAllPath).getParentFile().exists()) {
				new File(FPATH + fileAllPath).mkdirs();
			}

			file.transferTo(new File(FPATH + fileAllPath));
			if (fileVisitBasePath != null) {
				result = fileVisitBasePath + "/" + fileAllPath;
			} else {
				result = "upload/" + fileAllPath;
			}
			result=projectUrl+result;
			String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
			// 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
			PrintWriter out = response.getWriter();
			out.println("<script type=\"text/javascript\">");
			out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + result + "','')");
			out.println("</script>");

			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Object test(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "typename", required = false) String typename,
			@RequestParam(value = "isFile", required = false) Boolean isFile,
			@RequestParam(value = "fileType", required = false) String fileType) {
		String result = "";
		String path = "";
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(typename);// 获取表单
			String filename = multipartFile.getOriginalFilename();// 获取文件名

			String FPATH = this.getClass().getClassLoader().getResource("/").getPath().split("/WEB-INF/")[0]
					+ "/upload/";
			if (basePath != null) {
				FPATH = basePath + "/";
			}
			String originalFilename = multipartFile.getOriginalFilename();
			String extName = "";
			int lastIndexOf = originalFilename.lastIndexOf(".");
			if (lastIndexOf >= 0) {
				extName = originalFilename.substring(lastIndexOf);
			}
			String fileAllPath = path + "/" + UUID.randomUUID() + extName;
			if (!new File(FPATH + fileAllPath).getParentFile().exists()) {
				new File(FPATH + fileAllPath).mkdirs();
			}
			multipartFile.transferTo(new File(FPATH + fileAllPath));
			if (fileVisitBasePath != null) {
				result = fileVisitBasePath + "/" + fileAllPath;
			} else {
				result = "upload/" + fileAllPath;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
